package com.zlyx.easy.socket.core;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

import com.zlyx.easy.core.utils.ObjectUtils;
import com.zlyx.easy.socket.core.supports.AbstractMsgHandlerFactory;
import com.zlyx.easy.socket.interfaces.IMsgHandler;

/**
 * BIO方式处理UDP消息工厂
 * 
 * @author 赵光
 * @Description: BIO方式处理UDP消息工厂
 * @date 2018年11月14日
 */
public class BioUdpMsgHandlerFactory extends AbstractMsgHandlerFactory {

	DatagramSocket socket = null;
	DatagramPacket packet = null;
	byte[] data = null;

	public BioUdpMsgHandlerFactory(int port, float size, IMsgHandler<?> handler) throws Exception {
		super(port, size, handler);
		socket = new DatagramSocket(this.PORT);
		data = new byte[BLOCK];
		packet = new DatagramPacket(data, data.length);
	}

	@Override
	public boolean doBlock() throws Exception {
		socket.receive(packet);
		String msg = new String(data, 0, packet.getLength());
		byte[] res = doHandler(msg);
		if (ObjectUtils.isNotEmpty(res)) {
			DatagramPacket client = new DatagramPacket(res, res.length, packet.getAddress(), packet.getPort());
			socket.send(client);
		}
		return true;
	}

	@Override
	public void closeServer() throws Exception {
		if (socket != null) {
			socket.close();
		}
	}
}
